package com.example.controller;

import com.example.pojo.Category;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.CategoryService;
import com.example.service.UserService;
import com.example.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;
    @PostMapping("/add")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        categoryService.add(category);
        return Result.success();
    }

    // 查询所有分类（任何人都可以查询）
    @GetMapping ("/list")
    public Result list(){
        List<Category> categoryList = categoryService.list();
        return Result.success(categoryList);
    }

    @GetMapping("/detail")
    public Result detail(Integer id){
        Category category = categoryService.findById(id);
        return Result.success(category);
    }
    //更新（需要管理员权限）
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        else {
            categoryService.update(category);
            return Result.success();
        }
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer id){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        categoryService.delete(id);
        return Result.success();
    }


}
